package com.tianci.appstore.ui.list.scanapk;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.text.TextUtils.TruncateAt;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.XServiceManager;
import com.tianci.appstore.R;
import com.tianci.appstore.controller.manager.ScanAPKController;
import com.tianci.appstore.ui.SkinManager;
import com.tianci.appstore.ui.data.APKData;
import com.tianci.appstore.ui.data.SkyAppBaseData;
import com.tianci.appstore.ui.data.SkyAppDetailData.AppAction;
import com.tianci.appstore.ui.data.SkyAppDetailData.AppStatus;
import com.tianci.appstore.ui.data.SkyListAppData;
import com.tianci.appstore.ui.data.SkyListAppData.ListType;
import com.tianci.appstore.ui.data.SkyListStatusData;
import com.tianci.appstore.ui.dialog.ConfirmProcessDialog;
import com.tianci.appstore.ui.list.ListBlock;
import com.tianci.appstore.ui.list.ListFlipper;
import com.tianci.appstore.ui.list.ListStatusBlock;
import com.tianci.appstore.ui.list.manage.ManageBaseListView;
import com.tianci.appstore.ui.list.manage.ManageListController.SwitchFocusListener;
import com.tianci.appstore.ui.list.manage.MultiSelectUIListener;
import com.tianci.appstore.ui.util.UICommon;
import com.tianci.appstore.ui.widget.ColorButton;
import com.tianci.appstore.ui.widget.OnButtonClickListener;
import com.tianci.appstore.ui.widget.SkyCustomLayout;
import com.tianci.appstore.ui.widget.TipToast;
import com.tianci.appstore.utils.ImageUtils;
import com.tianci.appstore.utils.SkyConstants;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class ApkSearchListView extends ManageBaseListView implements OnButtonClickListener,
        ScanAPKListListener, OnClickListener, MultiSelectUIListener, SwitchFocusListener {
    protected static final int SCAN_FINISHED = 6;
    protected static final int REFRESH_SCAN_PATH = 7;
    private static final int HIDE_INSTALL_DLG = 8;
    private static final int UPDATE_INSTALL_RESULT = 9;
    private static final int INSTALL_ALL_BTN_ID = 1;

    private ConfirmProcessDialog dialog;
    private TextView loadingPartnerText;
    private TextView showPathText;
    // private Button installAllButton;
    private LinearLayout rightTopLayout;
    private Button selectButton;
    private Button cancelButton;
    private Button installButton;
    private boolean inSelectMode = false;
    private static final int SELECT_BTN_ID = 101;
    private static final int CANCEL_BTN_ID = 102;
    private static final int INSTALL_BTN_ID = 103;
    private LinearLayout.LayoutParams btnParams;

    private boolean canInstallSilent = false;
    private boolean scanFinished = false;
    private List<APKData> dataList;
    private List<SkyListAppData> selList;

    private StringBuffer dialogTitleStr;
    private boolean isSafeOn = false;
    private List<Bitmap> bitmapCornerList = null;

    public ApkSearchListView(Context context) {
        super(context, ListType.APK_SCAN_LIST);
        mController.setMultiSelectUIListener(this);
        mController.setSwitchFocusListener(this);
        isSafeOn = ScanAPKController.isAppSaferOpen(mContext);
        bitmapCornerList = new ArrayList<Bitmap>();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    canInstallSilent = CoocaaApplication.isRoot();
                    mainHandler.sendEmptyMessage(INIT_RIGHT_TOP);
                    LogUtils.d("safe", "initTopRightLayout canInstallSilent:" + canInstallSilent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
        createView();
        // TODO Auto-generated constructor stub
        startSearch();
    }

    private void createView() {
        loadingPartnerText = UICommon.newTextView(mContext, UICommon.tipTextSize, R.color.tipColor);
        loadingPartnerText.setText(R.string.scanning_apk);
        loadingPartnerText.setGravity(Gravity.CENTER);
        LayoutParams loadingPartnerParams = new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT, Gravity.CENTER);
        loadingPartnerParams.topMargin = SkyConstants.Div(36);
        this.addView(loadingPartnerText, loadingPartnerParams);
        loadingPartnerText.setVisibility(View.INVISIBLE);

        showPathText = UICommon.newTextView(mContext, SkyConstants.Dpi(45), R.color.tipColor);
        showPathText.setGravity(Gravity.CENTER);
        showPathText.setPadding(SkyConstants.Div(90), 0, SkyConstants.Div(90), 0);
        showPathText.setEllipsize(TruncateAt.MIDDLE);
        LayoutParams showPathParams = new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT, Gravity.CENTER);
        showPathParams.topMargin = SkyConstants.Div(99);
        this.addView(showPathText, showPathParams);
        showPathText.setVisibility(View.INVISIBLE);

        LayoutParams loadingParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT, Gravity.CENTER);
        loadingParams.bottomMargin = SkyConstants.Div(60);
        loadingView.setLayoutParams(loadingParams);

    }

    private void initTopRightLayout() {
        if (!(canInstallSilent && isSafeOn))
            return;

        rightTopLayout = new LinearLayout(mContext);
        rightTopLayout.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
        rightTopLayout.setPadding(0, 0, SkyConstants.Div(27), 0);

        LayoutParams topRightParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT, Gravity.TOP | Gravity.RIGHT);
        topRightParams.setMargins(0, SkyConstants.Div(87), SkyConstants.Div(75), 0);
        this.addView(rightTopLayout, topRightParams);

//        ImageView btnTopImage = new ImageView(mContext);
//        SkinManager.setBackground(btnTopImage, R.drawable.pic_line);
//        LayoutParams dividerParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
//                LayoutParams.WRAP_CONTENT, Gravity.TOP | Gravity.RIGHT);
//        dividerParams.setMargins(0, SkyConstants.Div(86), SkyConstants.Div(94), 0);
//        this.addView(btnTopImage, dividerParams);

        btnParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);
        // btnParams.setMargins(SkyConstants.Div(10), 0, SkyConstants.Div(10), 0);
        btnParams.weight = 1;
        selectButton = newButton(SELECT_BTN_ID, R.string.batch_install);
        setBtnEnabled(selectButton, false);
        rightTopLayout.addView(selectButton, btnParams);

        cancelButton = newButton(CANCEL_BTN_ID, R.string.cancel);
        cancelButton.setOnKeyListener(keyListener);
        installButton = newButton(INSTALL_BTN_ID, R.string.install);
        installButton.setOnKeyListener(keyListener);
        installButton.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View arg0, boolean hasFocus) {
                // TODO Auto-generated method stub
                if (hasFocus)
                    cancelButton.setFocusable(true);
            }
        });
        // installAllButton = UICommon.newButton(mContext, rightTopTextSize, R.color.btnColor);
        // SkinManager.setBackground(installAllButton, R.drawable.search_selector);
        // installAllButton.setPadding(SkyConstants.Div(27), 0, SkyConstants.Div(27),
        // SkyConstants.Div(6));
        // installAllButton.setText(R.string.install_all);
        // installAllButton.setId(INSTALL_ALL_BTN_ID);
        // installAllButton.setOnClickListener(this);
        // rightTopLayout.addView(installAllButton, new LinearLayout.LayoutParams(
        // LayoutParams.WRAP_CONTENT, SkyConstants.Div(80)));
    }

    private OnKeyListener keyListener = new OnKeyListener() {
        @Override
        public boolean onKey(View arg0, int keyCode, KeyEvent event) {
            // TODO Auto-generated method stub
            if (event.getAction() == KeyEvent.ACTION_UP) {
                if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
                    if (installButton.isEnabled())
                        cancelButton.setFocusable(false);
                }
            }
            return false;
        }
    };

    private Button newButton(int btnId, int strId) {
        Button btn = UICommon.newButton(mContext, rightTopTextSize, R.color.btnColor);
        SkinManager.setBackground(btn, R.drawable.search_selector);
        // btn.setPadding(SkyConstants.Div(27), 0, SkyConstants.Div(27), SkyConstants.Div(6));
        btn.setText(strId);
        btn.setId(btnId);
        btn.setOnClickListener(this);
        return btn;
    }

    private static final int INIT_RIGHT_TOP = 2;
    private Handler mainHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SCAN_FINISHED:
                    refreshListData((List<APKData>) msg.obj, (List<SkyListAppData>) msg.obj);
                    break;
                case REFRESH_SCAN_PATH:
                    setLoadingText();
                    break;
                case UPDATE_INSTALL_RESULT:
                    refreshInstallResult(msg.arg1, (List<APKData>) msg.obj);
                    break;
                case HIDE_INSTALL_DLG:
                    if (dialog != null)
                        dialog.hide();
                    break;
                case UPDATE_STATUS:
                    refreshStatus(msg.getData().getString("pkgName"),
                            msg.getData().getInt("version"), (AppStatus) msg.obj);
                    break;
                case INIT_RIGHT_TOP:
                    initTopRightLayout();
                    break;
            }
            super.handleMessage(msg);
        }
    };

    private void startSearch() {
        ScanAPKController.getInstance().init();
        ScanAPKController.getInstance().setScanAPKListener(this);
        ScanAPKController.getInstance().scanAPKOnThread();
        setLoadingVisible(true);
    }

    public void setLoadingVisible(boolean visible) {
        super.setLoadingVisible(visible);
        if (visible) {
            loadingPartnerText.setVisibility(View.VISIBLE);
            showPathText.setVisibility(View.VISIBLE);
        } else {
            loadingPartnerText.setVisibility(View.INVISIBLE);
            showPathText.setVisibility(View.INVISIBLE);
        }
    }

    private void setLoadingText() {
        showPathText.setText(crtPath);
    }

    private void setSelectMode(boolean selMode) {
        if (this.inSelectMode == selMode)
            return;
        this.inSelectMode = selMode;
        if (selMode) {
            if (rightTopLayout != null) {
                rightTopLayout.removeAllViews();
                rightTopLayout.addView(cancelButton, btnParams);
                rightTopLayout.addView(installButton, btnParams);
                setBtnEnabled(installButton, false);
            }

            setInSelectMode(selMode);
            for (int i = 0; i < listFlipper.getChildCount(); i++) {
                SkyCustomLayout child = (SkyCustomLayout) listFlipper.getChildAt(i);
                for (int j = 0; j < child.getChildCount(); j++) {
                    ListBlock block = (ListBlock) child.getChildAt(j);
                    block.refreshSelectState();
                }
            }
            mController.clearSelectedDataList();
            resetFocus();
        } else {
            if (rightTopLayout != null) {
                rightTopLayout.removeAllViews();
                rightTopLayout.addView(selectButton, btnParams);
            }
            mController.clearSelectedDataList();
            setInSelectMode(false);
            for (int i = 0; i < listFlipper.getChildCount(); i++) {
                SkyCustomLayout child = (SkyCustomLayout) listFlipper.getChildAt(i);
                for (int j = 0; j < child.getChildCount(); j++) {
                    ListBlock block = (ListBlock) child.getChildAt(j);
                    block.refreshSelectState();
                }
            }
            resetFocus();
        }
    }

    // 其实这两个dataList是同一个
    private void refreshListData(List<APKData> dataList, List<SkyListAppData> sameList) {
        setLoadingVisible(false);
        this.dataList = dataList;
        if (dataList == null || dataList.size() == 0) {
            if (selectButton != null) {
                setBtnEnabled(selectButton, false);
                rightTopLayout.removeAllViews();
                rightTopLayout.addView(selectButton, btnParams);
            }
            setEmptyTipVisible(true, mContext.getString(R.string.scan_0_apks));
        } else {
            setEmptyTipVisible(false, null);
            if (selectButton != null) {
                setBtnEnabled(selectButton, true);
                rightTopLayout.removeAllViews();
                rightTopLayout.addView(selectButton, btnParams);
            }
            mController.setDataList(sameList);
            resetFocus();
        }
        setSelected(false);
    }

    @Override
    public void onFinishScan(List<APKData> list) {
        // TODO Auto-generated method stub
        scanFinished = true;
        Message msg = mainHandler.obtainMessage(SCAN_FINISHED);
        msg.obj = list;
        mainHandler.sendMessage(msg);
    }

    @Override
    public void OnSelectCountChanged(int count) {
        // TODO Auto-generated method stub
        if (inSelectMode) {
            if (rightTopLayout != null)
                setBtnEnabled(installButton, count != 0);
        }
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            // case INSTALL_ALL_BTN_ID:
            // // 点击“全部安装”的处理
            // installCount = dataList.size();
            // initInstallDialog();
            // if(installCount > 1)
            // {
            // dialog.setIconTitle(SkinManager.getResDrawable(R.drawable.icon_scan),
            // mContext.getString(R.string.install_all));
            // String content = String.format(mContext.getString(
            // R.string.confirm_install_all), dataList.size());
            // dialog.setContent(content);
            // }
            // else{
            // APKData data = (APKData) dataList.get(0);
            // dialog.setIconTitle(((APKData)data).getIcon(), data.getTitle());
            // dialog.setContent(mContext.getString(R.string.confirm_install_apk));
            // }
            // dialog.setBtnFocusTag(1);
            // dialog.show();
            // break;
            case SELECT_BTN_ID:
                if (!inSelectMode)
                    setSelectMode(!inSelectMode);
                break;
            case CANCEL_BTN_ID:
                if (inSelectMode) {
                    setSelectMode(!inSelectMode);
                    resetFocus();
                }
                break;
            case INSTALL_BTN_ID: {
                List<SkyListAppData> selectList = mController.getSelectedDataList();
                int selSize = selectList.size();
                installCount = selSize;
                initInstallDialog();
                lastFocusIndex = -1;
                lastFocusPageIndex = -1;
                if (selSize > 1) {
                    dialog.setIconTitle(mContext.getResources().getDrawable(R.drawable.icon_scan),
                            mContext.getResources().getString(R.string.install_apk));
                    dialogTitleStr = new StringBuffer(selectList.get(0).getTitle());
                    dialogTitleStr.append(mContext.getString(R.string.pause_mark));
                    dialogTitleStr.append(selectList.get(1).getTitle());
                    if (selSize > 2) {
                        dialogTitleStr.append(mContext.getString(R.string.and_so_on));
                    }
                    String contentStr = String.format(
                            mContext.getResources().getString(R.string.install_batch_tip),
                            dialogTitleStr, selSize);
                    dialog.setContent(contentStr);
                } else {
                    SkyListAppData selData = mController.getSelectedDataList().get(0);
                    selectData.clear();
                    selectData.add((APKData) selData);
                    dialog.setIconTitle(selData, selData.getTitle());
                    dialog.setContent(mContext.getString(R.string.confirm_install_apk));
                }
                dialog.setBtnFocusTag(1);
                dialog.show();
            }
            break;
        }
    }

    @Override
    public void destroyController() {
        // TODO Auto-generated method stub
        ScanAPKController.getInstance().destroy();
        if (dialog != null)
            dialog.onDestory();
        if (bitmapCornerList.size() > 0) {
            Bitmap bm = null;
            for (int i = bitmapCornerList.size() - 1; i >= 0; i--) {
                bm = bitmapCornerList.get(i);
                bitmapCornerList.remove(bm);
                if (bm != null && !bm.isRecycled()) {
                    bm.recycle();
                    bm = null;
                }
            }
            bitmapCornerList.clear();
        }
        super.destroyController();
    }

    @Override
    public boolean processKeyDown(int keyCode) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (inSelectMode) {
                setSelectMode(!inSelectMode);
                return true;
            }
        }
        return false;
    }

    private APKData clickedAPKData;
    private int installCount = 0;
    private List<APKData> selectData = new ArrayList<APKData>();

    @Override
    public void onBlockClicked(View v, SkyListAppData data, int index) {
        // TODO Auto-generated method stub
        if (selectData.size() > 0)
            selectData.clear();
        selectData.add((APKData) data);
        clickedAPKData = (APKData) data;
        LogUtils.d("scan", "onBlockClicked   ");
        if (((SkyListStatusData) data).getStatus().equals(AppStatus.INSTALLED)
                || ((SkyListStatusData) data).getStatus().equals(AppStatus.INSTALLED_WITH_CAN_NOT_BE_UNINSTALLED)) {
//            TipToast.getInstance(mContext).showToast(((APKData) data).getIcon(),
//                    mContext.getString(R.string.xx_installed), 2000, Gravity.CENTER);
            try {
                LogUtils.d("scan", "start app!!");
                XServiceManager.getLitePMService().startApp(mContext.getClass().getName(), false, data.getPkgName());
            } catch (RemoteException e) {
                LogUtils.d("scan", "start app error!!");
                e.printStackTrace();
            }
            return;
        }
        if (canInstallSilent && isSafeOn) {
            installCount = 1;
            initInstallDialog();
            dialog.setIconTitle(((APKData) data).getIcon(), data.getTitle());
            dialog.setContent(mContext.getString(R.string.confirm_install_apk));
            dialog.setBtnFocusTag(1);
            dialog.show();
        } else {
            // ScanAPKController.getInstance().resetInstallList(selectData);
            ScanAPKController.getInstance().installAPKList(selectData);
        }
    }

    private void initInstallDialog() {
        if (dialog == null) {
            dialog = new ConfirmProcessDialog(mContext);
            dialog.setButtonClickListener(this);
            dialog.addButton(AppAction.ACTION_CANCEL, 0, false);
            dialog.addButton(AppAction.ACTION_INSTALL, 1, true);
        } else {
            dialog.removeAllBtns();
            dialog.addButton(AppAction.ACTION_CANCEL, 0, false);
            dialog.addButton(AppAction.ACTION_INSTALL, 1, true);
            dialog.initStatus();
        }
    }

    @Override
    public void onClick(int index) {
        // TODO Auto-generated method stub
        if (index == 0) {
            if (dialog != null)
                dialog.dismiss();
        } else if (index == 1) {
            LogUtils.d("hhhh", "------------install btn clicked-------------");
            String installingStr = "";
            if (installCount > 1) {
                Object obj = mController.getSelectedDataList();
                selectData = (List<APKData>) obj;
                for (APKData data : selectData) {
                    LogUtils.d("hhhh", "selected title = " + data.getTitle());
                }
                installingStr = String.format(
                        mContext.getResources().getString(R.string.installing_xx_apps),
                        dialogTitleStr, selectData.size());
                // ScanAPKController.getInstance().resetInstallList(selectData);
                ScanAPKController.getInstance().installAPKList(selectData);
            } else {
                // ScanAPKController.getInstance().resetInstallList(selectData);
                ScanAPKController.getInstance().installAPKList(selectData);
                installingStr = mContext.getString(R.string.installing_xx_app);
            }
            if (dialog != null)
                dialog.enterWaitState(installingStr);
        }
    }

    private String crtPath;
    private long lastUpdateTime;

    @Override
    public void onShowCurrentPath(String path) {
        // TODO Auto-generated method stub
        long time = Calendar.getInstance().getTimeInMillis();
        if (Math.abs(time - lastUpdateTime) > 50) {
            crtPath = path;
            mainHandler.sendEmptyMessage(REFRESH_SCAN_PATH);
            lastUpdateTime = time;
        }
    }

    @Override
    public void onInstallFinished(int successCount, List<APKData> failList) {
        if (!scanFinished)
            return;
        Message msg = mainHandler.obtainMessage(UPDATE_INSTALL_RESULT);
        msg.arg1 = successCount;
        msg.obj = failList;
        mainHandler.sendMessage(msg);
    }

    private void refreshInstallResult(int successCount, List<APKData> failList) {
        // TODO Auto-generated method stub
        String contentStr = "";
        boolean allSuccess = true;
        if (successCount < installCount && failList != null && failList.size() > 0) {
            allSuccess = false;
            StringBuffer failTitleListStr = new StringBuffer();
            int i = 0;
            for (SkyListAppData data : failList) {
                if (i < failList.size() - 1)
                    failTitleListStr.append(data.getTitle() + ",");
                else
                    failTitleListStr.append(data.getTitle());
                i++;
            }
            contentStr = String.format(mContext.getResources().getString(R.string.install_result),
                    successCount, installCount - successCount, failTitleListStr);
            Object failObj = failList;
            mController.setSelectedDataList((List<SkyListAppData>) failObj);
            Object dataObj = dataList;
            mController.setDataList((List<SkyListAppData>) dataObj);
        } else {
            if (installCount == 1)
                contentStr = String.format(mContext.getString(R.string.install_finish), "");
            else {
                contentStr = String.format(mContext.getString(R.string.install_finish),
                        dialogTitleStr);
            }
            setSelectMode(false);
        }
        if (dialog != null) {
            dialog.enterResultState(contentStr);
            if (!allSuccess) {
                dialog.removeAllBtns();
                dialog.addButton(new ColorButton(mContext, R.string.confirm, R.drawable.btn_green,
                        R.drawable.btn_green_focus), 2, true);
            } else {
                mainHandler.sendEmptyMessageDelayed(HIDE_INSTALL_DLG, 1500);
            }
        }
    }

    @Override
    public void onUpdateStatus(String pkgName, int version, AppStatus status) {
        // TODO Auto-generated method stub
        LogUtils.d("hhhh", "update status, pkgName = " + pkgName + ", status = " + status);
        if (!scanFinished)
            return;
        Message msg = mainHandler.obtainMessage(UPDATE_STATUS);
        msg.obj = status;
        Bundle bundle = new Bundle();
        bundle.putString("pkgName", pkgName);
        bundle.putInt("version", version);
        msg.setData(bundle);
        mainHandler.sendMessage(msg);
    }

    protected void refreshStatus(String pkgName, int version, AppStatus status) {
        PackageManager pm = mContext.getPackageManager();
        LogUtils.d("install", "refreshStatus  pkg:" + pkgName + " version:" + version + " status:" + status.toString());
        for (int i = 0; i < ListFlipper.VIEW_PAGE_COUNT; i++) {
            SkyCustomLayout child = (SkyCustomLayout) listFlipper.getChildAt(i);
            for (View view : child.getChildViews()) {
                ListStatusBlock block = (ListStatusBlock) view;
                SkyAppBaseData baseData = block.getData();
                if (baseData != null) {
                    APKData apkData = (APKData) baseData;
//                    boolean versionEquals = true;
//                    if (version != null && version.trim().length() > 0
//                            && !version.equals(apkData.getVersionName()))
//                        versionEquals = false;
                    if (pkgName.equals(apkData.getPkgName()))//&& versionEquals)
                    {
                        if (status == AppStatus.NOT_DOWNLOADED)
                            block.updateStatus(status);
                        else if (status == AppStatus.INSTALLED) {
                            int versionCode = getVersionCode(pm, apkData.getPath());
                            if (version >= versionCode)
                                block.updateStatus(AppStatus.INSTALLED);
                            else
                                block.updateStatus(AppStatus.HAS_NEW_VERSION);
                        } else if (status == AppStatus.HAS_NEW_VERSION) {
                            int versionCode = getVersionCode(pm, apkData.getPath());
                            if (version <= versionCode)
                                block.updateStatus(AppStatus.HAS_NEW_VERSION);
                            else
                                block.updateStatus(AppStatus.INSTALLED);
                        }
                    }
                }
            }
        }
    }

    private int getVersionCode(PackageManager pm, String apkPath) {
        if (pm == null)
            pm = mContext.getPackageManager();
        PackageInfo pkgInfo = pm.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
        if (pkgInfo != null) {
            return pkgInfo.versionCode;
        }
        return 0;
    }

    // 在批量安装状态下，已经安装的应用不可勾选。return false即不可勾选，return true则可选中
    @Override
    public boolean checkSelectable(SkyListAppData data, int index) {
        // TODO Auto-generated method stub
        if (((SkyListStatusData) data).getStatus().equals(AppStatus.INSTALLED)
                || ((SkyListStatusData) data).getStatus().equals(AppStatus.HAS_NEW_VERSION)) {
            Drawable drawable;
            try {
                BitmapDrawable bd = (BitmapDrawable) (((APKData) data).getIcon());
                Bitmap bm = bd.getBitmap();
                Bitmap bmCorner = ImageUtils.getRoundedCornerBitmap(bm, 25);
                bitmapCornerList.add(bmCorner);
                drawable = new BitmapDrawable(mContext.getResources(), bmCorner);
            } catch (Exception e) {
                drawable = ((APKData) data).getIcon();
            }
            TipToast.getInstance(mContext).showToast(drawable,
                    mContext.getString(R.string.xx_installed), Gravity.CENTER, 2000);
            return false;
        }
        return true;
    }

    // 保证在选择状态时，选好了应用，按“上”键会首先聚焦至“安装”按钮，而非“取消”按钮
    @Override
    public boolean switchFocus(int direction) {
        // TODO Auto-generated method stub
        if (direction == KeyEvent.KEYCODE_DPAD_UP) {
            if (installButton != null && installButton.isEnabled()
                    && installButton.getParent() != null) {
                installButton.requestFocus();
                return true;
            }
        }
        return false;
    }

    @Override
    public void onItemAudioMatch(SkyAppBaseData data, int index) {
        selectData.clear();
        selectData.add((APKData) data);
        ScanAPKController.getInstance().installAPKList(selectData);
    }

}
